using System;
using System.Collections.Generic;
using UnityEngine;
using QFramework;
using Random = UnityEngine.Random;

namespace ProjectSurvivor
{
	public partial class SimpleRotateSword : ViewController
	{
		
		private List<Collider2D> mRotateSwords = new List<Collider2D>();
		
		void Start()
		{
			RotateSword.Hide();
			
			// 守卫剑数量变化
			Global.SimpleRotateSwordCount.Or(Global.AdditionFlyingCount).Register(createRotateSwords)
				.UnRegisterWhenGameObjectDestroyed(gameObject);

			createRotateSwords();
			
			// 守卫剑半径变化
			Global.SimpleRotateSwordRange.Register(range =>
			{
				UpdateCirclePos();
			}).UnRegisterWhenGameObjectDestroyed(gameObject);
		}

		void UpdateCirclePos()
		{
			float radius = Global.SimpleRotateSwordRange.Value;
			float durationDegree = 360f / mRotateSwords.Count;
			
			for (var i = 0; i < mRotateSwords.Count; i++)
			{
				Vector2 circleLocalPos = new Vector2(Mathf.Cos(durationDegree * i * Mathf.Deg2Rad),
					Mathf.Sin(durationDegree * i * Mathf.Deg2Rad)) * radius;

				RotateSword.LocalPosition2D(circleLocalPos)
					.LocalEulerAnglesZ(durationDegree * i - 90);
			}
		}

		// 创建守卫剑
		private void createRotateSword()
		{
			int damageTimes = Global.SuperSimpleRotateSword.Value ? Random.Range(2, 4) : 1;
			
			var rotateSword = RotateSword.InstantiateWithParent(this)
				.Self(self =>
				{
					// 触碰到敌人
					self.OnTriggerEnter2DEvent(collider2D =>
					{
						var hurtbox = collider2D.GetComponent<HitHurtBox>();
						if (hurtbox && hurtbox.Owner.CompareTag("Enemy"))
						{
							DamageSystem.CalculateDamage(Global.SimpleRotateSwordDamage.Value * damageTimes, hurtbox.Owner.GetComponent<IEnemy>());
							
							// 一定概率击退敌人
							if (Random.Range(0f, 1f) < 0.5f&& collider2D && collider2D.attachedRigidbody && Player.Default)
							{
								collider2D.attachedRigidbody.velocity =
									collider2D.Direction2DFrom(self).normalized * 5 + 
									collider2D.Direction2DFrom(Player.Default).normalized * 10;
							}
						}
					}).UnRegisterWhenGameObjectDestroyed(self);
				})
				.Show();
			mRotateSwords.Add(rotateSword);
		}
		
		private void createRotateSwords()
		{
			int toAddCount = Global.SimpleRotateSwordCount.Value + Global.AdditionFlyingCount.Value - mRotateSwords.Count;

			for (int i = 0; i < toAddCount; i++)
			{
				createRotateSword();
			}
				
			UpdateCirclePos();
		}

		private void Update()
		{
			int speedTimes = Global.SuperSimpleRotateSword.Value ? Random.Range(2, 4) : 1;
			float degree = Time.frameCount * Global.SimpleRotateSwordSpeed.Value * speedTimes;

			this.LocalEulerAnglesZ(-degree);
		}
	}
}
